import React, { useState, useEffect } from 'react';

import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Search as SearchIcon,
} from '@mui/icons-material';
import {
  Box,
  Grid,
  Card,
  Chip,
  Alert,
  Button,
  Select,
  Tooltip,
  MenuItem,
  TextField,
  Typography,
  IconButton,
  InputLabel,
  Pagination,
  CardContent,
  FormControl,
  InputAdornment,
} from '@mui/material';

import { safeApiCall, getAuthHeader } from 'src/utils/api'

import {
  deleteTemplate,
  createRuleFromTemplate,
} from 'src/api/auto-accounting';

import { Iconify } from 'src/components/iconify';

import { AutoAccountingTemplateEditDialog } from './auto-accounting-template-edit-dialog'

interface AutoAccountingRuleTemplate {
  id: string;
  templateName: string;
  templateCategory: string;
  templateDescription: string;
  ruleConfig: string;
  usageCount: number;
  isPublic: boolean;
  createBy: string;
  creationDate: string;
}

interface PageInfo {
  list: AutoAccountingRuleTemplate[];
  pageNum: number;
  pageSize: number;
  total: number;
  pages: number;
  hasNextPage: boolean;
  hasPreviousPage: boolean;
}

export function AutoAccountingTemplates() {
  const [templates, setTemplates] = useState<AutoAccountingRuleTemplate[]>([]);
  const [pageInfo, setPageInfo] = useState<PageInfo>({
    list: [],
    pageNum: 1,
    pageSize: 12,
    total: 0,
    pages: 0,
    hasNextPage: false,
    hasPreviousPage: false,
  });
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<AutoAccountingRuleTemplate | null>(null);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

  const fetchTemplates = async (page = 1, size = 12) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        pageNumber: page.toString(),
        pageSize: size.toString(),
      });

      if (searchKeyword) params.append('keyword', searchKeyword);
      if (categoryFilter) params.append('category', categoryFilter);

      const result = await safeApiCall(`/api/auto-accounting/templates/paged?${params.toString()}`, 'GET', null, getAuthHeader());

      if (result.data.code === 200) {
        const data = result.data.data;
        console.log(data);
        setTemplates(data.list || []);
        setPageInfo({
          list: data.list || [],
          pageNum: data.pageNum || 1,
          pageSize: data.pageSize || 12,
          total: data.total || 0,
          pages: data.pages || 0,
          hasNextPage: data.hasNextPage || false,
          hasPreviousPage: data.hasPreviousPage || false,
        });
        setMessage('模板加载成功');
        setSeverity('success');
      } else {
        setMessage(result.data.message || '获取模板失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error fetching templates:', error);
      setMessage('获取模板失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTemplates();
  }, []);

  const handlePageChange = async (event: React.ChangeEvent<unknown>, page: number) => {
    await fetchTemplates(page, pageInfo.pageSize);
  };

  const handleSearch = async () => {
   await fetchTemplates(1, pageInfo.pageSize);
  };

  const handleEditTemplate = (template: AutoAccountingRuleTemplate) => {
    setSelectedTemplate(template);
    setEditDialogOpen(true);
  };

  const handleDeleteTemplate = async (templateId: string) => {
    if (!window.confirm('确定要删除这个模板吗？')) return;

    try {
      setLoading(true);
      const result = await deleteTemplate(templateId);

      if (result.code === '00000') {
        setMessage('模板删除成功');
        setSeverity('success');
        fetchTemplates(pageInfo.pageNum, pageInfo.pageSize);
      } else {
        setMessage(result.message || '删除模板失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error deleting template:', error);
      setMessage('删除模板失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateRule = async (template: AutoAccountingRuleTemplate) => {
    try {
      setLoading(true);
      const result = await createRuleFromTemplate(template.id);

      if (result.code === '00000') {
        setMessage('规则创建成功');
        setSeverity('success');
      } else {
        setMessage(result.message || '创建规则失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error creating rule:', error);
      setMessage('创建规则失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  const handleEditSuccess = () => {
    setEditDialogOpen(false);
    setSelectedTemplate(null);
    fetchTemplates(pageInfo.pageNum, pageInfo.pageSize);
  };

  const getCategoryColor = (category: string) => {
    const colors: { [key: string]: 'primary' | 'secondary' | 'success' | 'error' | 'warning' | 'info' } = {
      'EXPENSE': 'error',
      'INCOME': 'success',
      'TRANSPORT': 'primary',
      'FOOD': 'warning',
      'LIVING': 'info',
      'ENTERTAINMENT': 'secondary',
      'OTHER': 'info',
    };
    return colors[category] || 'info';
  };

  const getCategoryLabel = (category: string) => {
    const labels: { [key: string]: string } = {
      'EXPENSE': '支出',
      'INCOME': '收入',
      'TRANSPORT': '交通',
      'FOOD': '餐饮',
      'LIVING': '生活',
      'ENTERTAINMENT': '娱乐',
      'OTHER': '其他',
    };
    return labels[category] || category;
  };

  return (
    <Box>
      {message && (
        <Alert severity={severity} sx={{ mb: 2 }} onClose={() => setMessage('')}>
          {message}
        </Alert>
      )}

      {/* 搜索和过滤 */}
      <Card sx={{ mb: 3, borderRadius: 3, boxShadow: '0 2px 12px rgba(0, 0, 0, 0.06)' }}>
        <CardContent sx={{ p: 3 }}>
          <Grid container spacing={3} alignItems="center">
            <Grid item xs={12} md={4}>
              <TextField
                fullWidth
                placeholder="搜索模板..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <SearchIcon sx={{ color: 'text.secondary' }} />
                    </InputAdornment>
                  ),
                }}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    borderRadius: 2,
                    '&:hover': {
                      '& .MuiOutlinedInput-notchedOutline': {
                        borderColor: 'primary.light',
                      },
                    },
                  },
                }}
              />
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>分类筛选</InputLabel>
                <Select
                  value={categoryFilter}
                  onChange={(e) => setCategoryFilter(e.target.value)}
                  label="分类筛选"
                  sx={{
                    borderRadius: 2,
                    '& .MuiOutlinedInput-notchedOutline': {
                      borderColor: 'divider',
                    },
                  }}
                >
                  <MenuItem value="">全部分类</MenuItem>
                  <MenuItem value="EXPENSE">支出</MenuItem>
                  <MenuItem value="INCOME">收入</MenuItem>
                  <MenuItem value="TRANSPORT">交通</MenuItem>
                  <MenuItem value="FOOD">餐饮</MenuItem>
                  <MenuItem value="LIVING">生活</MenuItem>
                  <MenuItem value="ENTERTAINMENT">娱乐</MenuItem>
                  <MenuItem value="OTHER">其他</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={2}>
              <Button
                fullWidth
                variant="contained"
                onClick={handleSearch}
                disabled={loading}
                sx={{
                  borderRadius: 2,
                  textTransform: 'none',
                  fontWeight: 600,
                  height: 48,
                  background: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                  '&:hover': {
                    background: 'linear-gradient(135deg, #43a3f0 0%, #00e6f0 100%)',
                    transform: 'translateY(-1px)',
                    boxShadow: '0 4px 12px rgba(79, 172, 254, 0.4)',
                  },
                }}
              >
                搜索
              </Button>
            </Grid>
            <Grid item xs={12} md={3}>
              <Button
                fullWidth
                variant="outlined"
                startIcon={<AddIcon />}
                onClick={() => {
                  setSelectedTemplate(null);
                  setEditDialogOpen(true);
                }}
                sx={{
                  borderRadius: 2,
                  textTransform: 'none',
                  fontWeight: 600,
                  height: 48,
                  borderWidth: 2,
                  borderColor: 'primary.main',
                  color: 'primary.main',
                  '&:hover': {
                    borderWidth: 2,
                    backgroundColor: 'primary.light',
                    color: 'primary.contrastText',
                    transform: 'translateY(-1px)',
                    boxShadow: '0 4px 12px rgba(25, 118, 210, 0.3)',
                  },
                }}
              >
                新建模板
              </Button>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 模板列表 */}
      <Grid container spacing={3}>
        {templates.map((template) => (
          <Grid item xs={12} sm={6} md={4} key={template.id}>
            <Card 
              sx={{ 
                height: '100%', 
                display: 'flex', 
                flexDirection: 'column',
                borderRadius: 3,
                boxShadow: '0 4px 20px rgba(0, 0, 0, 0.08)',
                transition: 'all 0.3s ease-in-out',
                border: '1px solid',
                borderColor: 'divider',
                '&:hover': {
                  transform: 'translateY(-4px)',
                  boxShadow: '0 8px 30px rgba(0, 0, 0, 0.12)',
                  borderColor: 'primary.light',
                },
                position: 'relative',
                overflow: 'hidden',
              }}
            >
              {/* 顶部装饰条 */}
              <Box
                sx={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  height: 4,
                  background: `linear-gradient(90deg, ${getCategoryColor(template.templateCategory) === 'primary' ? '#1976d2' : 
                    getCategoryColor(template.templateCategory) === 'success' ? '#2e7d32' : 
                    getCategoryColor(template.templateCategory) === 'error' ? '#d32f2f' : 
                    getCategoryColor(template.templateCategory) === 'warning' ? '#ed6c02' : 
                    getCategoryColor(template.templateCategory) === 'info' ? '#0288d1' : '#9c27b0'}, 20%)`,
                }}
              />
              
              <CardContent sx={{ 
                flexGrow: 1, 
                display: 'flex', 
                flexDirection: 'column',
                p: 3,
                pt: 4,
              }}>
                {/* 头部区域 */}
                <Box display="flex" justifyContent="space-between" alignItems="flex-start" mb={2}>
                  <Box sx={{ flex: 1, mr: 1 }}>
                    <Typography 
                      variant="h6" 
                      component="h3" 
                      sx={{ 
                        fontWeight: 600,
                        color: 'text.primary',
                        lineHeight: 1.3,
                        mb: 0.5,
                      }}
                    >
                      {template.templateName}
                    </Typography>
                    <Chip
                      label={getCategoryLabel(template.templateCategory)}
                      color={getCategoryColor(template.templateCategory)}
                      size="small"
                      sx={{ 
                        fontWeight: 500,
                        fontSize: '0.75rem',
                        height: 24,
                      }}
                    />
                  </Box>
                  
                  {/* 操作按钮 */}
                  <Box display="flex" gap={0.5}>
                    <Tooltip title="编辑模板" arrow>
                      <IconButton
                        size="small"
                        onClick={() => handleEditTemplate(template)}
                        sx={{
                          backgroundColor: 'action.hover',
                          '&:hover': {
                            backgroundColor: 'primary.light',
                            color: 'primary.contrastText',
                          },
                        }}
                      >
                        <EditIcon fontSize="small" />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title="删除模板" arrow>
                      <IconButton
                        size="small"
                        color="error"
                        onClick={() => handleDeleteTemplate(template.id)}
                        sx={{
                          backgroundColor: 'error.light',
                          color: 'error.contrastText',
                          '&:hover': {
                            backgroundColor: 'error.main',
                          },
                        }}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  </Box>
                </Box>

                {/* 描述区域 */}
                <Typography 
                  variant="body2" 
                  color="text.secondary" 
                  sx={{ 
                    mb: 3, 
                    flexGrow: 1,
                    lineHeight: 1.6,
                    minHeight: '3.2em',
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                  }}
                >
                  {template.templateDescription || '暂无描述'}
                </Typography>

                {/* 统计信息 */}
                <Box 
                  sx={{ 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center', 
                    mb: 3,
                    p: 2,
                    backgroundColor: 'grey.50',
                    borderRadius: 2,
                    border: '1px solid',
                    borderColor: 'divider',
                  }}
                >
                  <Box display="flex" alignItems="center" gap={1}>
                    <Iconify icon="eva:trending-up-fill" sx={{ fontSize: 16, color: 'success.main' }} />
                    <Typography variant="caption" color="text.secondary" sx={{ fontWeight: 500 }}>
                      使用 {template.usageCount} 次
                    </Typography>
                  </Box>
                  <Chip
                    label={template.isPublic ? '公开' : '私有'}
                    size="small"
                    variant="outlined"
                    color={template.isPublic ? 'success' : 'default'}
                    sx={{ 
                      fontSize: '0.7rem',
                      height: 20,
                      '& .MuiChip-label': { px: 1 },
                    }}
                  />
                </Box>

                {/* 操作按钮 */}
                <Box display="flex" gap={1.5}>
                  <Button
                    variant="contained"
                    size="medium"
                    fullWidth
                    onClick={() => handleCreateRule(template)}
                    disabled={loading}
                    sx={{
                      borderRadius: 2,
                      textTransform: 'none',
                      fontWeight: 600,
                      height: 40,
                      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                      '&:hover': {
                        background: 'linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%)',
                        transform: 'translateY(-1px)',
                        boxShadow: '0 4px 12px rgba(102, 126, 234, 0.4)',
                      },
                    }}
                  >
                    创建规则
                  </Button>
                  <Tooltip 
                    title="复制模板" 
                    placement="top"
                    arrow
                    enterDelay={500}
                    leaveDelay={200}
                  >
                    <Button
                      variant="outlined"
                      size="medium"
                      onClick={() => {
                        setSelectedTemplate({ ...template, id: '' });
                        setEditDialogOpen(true);
                      }}
                      sx={{
                        borderRadius: 2,
                        textTransform: 'none',
                        fontWeight: 600,
                        height: 40,
                        borderWidth: 2,
                        minWidth: 48,
                        px: 2,
                        '&:hover': {
                          borderWidth: 2,
                          transform: 'translateY(-1px)',
                          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                        },
                      }}
                    >
                      <Iconify icon="eva:copy-fill" />
                    </Button>
                  </Tooltip>
                </Box>
              </CardContent>
            </Card>
          </Grid>
        ))}
      </Grid>

      {/* 分页 */}
      {pageInfo.pages > 1 && (
        <Box display="flex" justifyContent="center" mt={3}>
          <Pagination
            count={pageInfo.pages}
            page={pageInfo.pageNum}
            onChange={handlePageChange}
            color="primary"
          />
        </Box>
      )}

      <AutoAccountingTemplateEditDialog
        open={editDialogOpen}
        onClose={() => {
          setEditDialogOpen(false);
          setSelectedTemplate(null);
        }}
        onSuccess={handleEditSuccess}
        template={selectedTemplate}
      />
    </Box>
  );
}
